<template>
  <div class="my-dropdown">
    <Tooltip ref="tooltipRef" :trigger="trigger" :placement="placement" :popper-options="popperOptions"
      :open-delay="openDelay" :close-delay="closeDelay" @visible-change="visibleChange">
      <slot></slot>
      <template #content>
        <ul class="my-dropdown__menu">
          <template v-for="item in menuOptions" :key="item.key">
            <li v-if="item.divided" role="separator" class="divided-placeholder"></li>
            <li :id="`dropdown-item-${item.key}`" class="my-dropdown__item" :class="{
              'is-disabled': item.disabled,
              'is-divided': item.divided
            }" @click="itemClick(item)">
              <RenderVnode :v-node="item.label" />
            </li>
          </template>
        </ul>
      </template>
    </Tooltip>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Tooltip from '../Tooltip/Tooltip.vue'
import type { DropdownEmits, DropdownInstance, DropdownProps, MenuOption } from './types'
import type { TooltipInstance } from '../Tooltip/types'
import RenderVnode from '../Common/RenderVnode'
defineOptions({
  name: 'MyDropdown'
})
const props = withDefaults(defineProps<DropdownProps>(), {
  hideAfterClick: true
})
const emits = defineEmits<DropdownEmits>()
const tooltipRef = ref<TooltipInstance>()


const visibleChange = (e: boolean) => {
  emits('visible-change', e)
}

const itemClick = (e: MenuOption) => {
  if (e.disabled) {
    return
  }
  emits('select', e)
  if (props.hideAfterClick) {
    tooltipRef.value?.hide()
  }
}

defineExpose<DropdownInstance>({
  show: () => tooltipRef.value?.show(),
  hide: () => tooltipRef.value?.hide()
})
</script>

<style scoped></style>